<template>
  <el-card shadow="hover">
    <el-button
      :icon="Plus"
      type="primary"
      :disabled="!categoryStore.category3Id"
      @click="showAddOrUpdateAttr()"
      >添加属性</el-button
    >
    <el-table :data="attrList" border style="width: 100%">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="attrName" label="属性名称" width="180" />
      <el-table-column label="属性值列表">
        <template v-slot="{ row }">
          <el-tag
            class="tag-10"
            type="success"
            v-for="attr in row.attrValueList"
            :key="attr.id"
            >{{ attr.valueName }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" align="center">
        <template v-slot="{ row }">
          <el-button
            :icon="Edit"
            type="warning"
            size="small"
            @click="showAddOrUpdateAttr(row)"
          ></el-button>
          <el-popconfirm
            :title="`确认删除${row.attrName}吗?`"
            @confirm="confirmEvent(row)"
          >
            <template #reference>
              <el-button :icon="Delete" type="danger" size="small"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script lang="ts" setup>
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ref, watch, onMounted } from "vue";
import { useCategoryStore } from "@/stores/category";
import {
  getCategoryBasicAttrApi,
  deleteOneAttrApi,
} from "@/api/product/category";
import { useAttrStore } from "@/stores/attr";
import type {
  CategoryBasicAttrItem,
  CategoryBasicAttrRes,
} from "@/api/product/modules/categoryModules";
defineOptions({
  name: "AttrList",
});
const categoryStore = useCategoryStore();
const attrList = ref<CategoryBasicAttrRes>([]);

const getAttrList = async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  if (!category3Id) {
    attrList.value = [];
    return;
  }
  const result = await getCategoryBasicAttrApi(
    category1Id as number,
    category2Id as number,
    category3Id as number
  );
  attrList.value = result;
};
onMounted(getAttrList); // 父组件用v-if-else控制此组件的显示或隐藏，故此需要挂载时候重新请求数据
watch(() => categoryStore.category3Id, getAttrList);

const emit = defineEmits(["setShowAttrList"]);

const attrStore = useAttrStore();

// 点击添加属性其内容显示为空，点击修改有内容
const showAddOrUpdateAttr = (
  row: CategoryBasicAttrItem = { attrName: "", attrValueList: [] }
) => {
  emit("setShowAttrList", false);
  attrStore.id = row.id;
  attrStore.attrName = row.attrName;
  attrStore.attrValueList = row.attrValueList;
};

// 删除一条属性
const confirmEvent = async (row: { id: number }) => {
  await deleteOneAttrApi(row.id);
  ElMessage({
    type: "success",
    message: "删除成功",
  });
  getAttrList();
};
</script>

<style scoped lang="scss">
.tag-10 {
  margin-right: 10px;
}
</style>
